%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%      DATA PREPARATION: Table 4  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [yy, ylag, tlag, ws, wn] = prepdat4(gdp, ter, invst, pop, tcap, differ)

%%%----------------------------------------------------------------
%%% gdp - GDP per capita
%%% ter - terrorist attacks
%%% invst - investment
%%% pop - population
%%% tcap = 1 if terrorism to be divided by 1000; 2 = ter/pop
%%% differ = 1 if terrorism to be at level; 2 = first differenced
%%%-----------------------------------------------------------------

y1 = gdp;
if tcap == 1; ter1 = ter/1000;
elseif tcap==2; ter1=ter./pop; end
 
T = length(y1);
wy = log(y1);
ws = log(invst.*gdp/100); % investment (in $) (they are in %)
wn = log(pop);
wn = wn(2:T,:) - wn(1:T-1,:); %pop. growth; loose 1 obs.

% First difference
wy = wy(2:T,:) - wy(1:T-1,:);
ws = ws(2:T,:) - ws(1:T-1,:);
wn = wn(2:T-1,:) - wn(1:T-2,:);
if differ == 1; wt = ter1(2:T,:); 
elseif differ==2; wt = ter1(2:T,:) - ter1(1:T-1,:); end 

T = length(wy); % We loose 1 year in 1st differencing

% Lagged variables
yy = wy(2:T,:); % loose 1 year because ylag & tlag below
ylag = wy(1:T-1,:); 
tlag = wt(1:T-1,:); 
ws = ws(2:T,:); % loose 1 year because ylag & tlag 
wn = wn(1:T-1,:); % already 1 year less; computed pop. growth 

% Demean
yy = yy - repmat(mean(yy),T-1,1);
ylag = ylag - repmat(mean(ylag),T-1,1);
tlag = tlag - repmat(mean(tlag),T-1,1);
ws = ws - repmat(mean(ws),T-1,1);
wn = wn - repmat(mean(wn),T-1,1);